package com.example.sys.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.common.utils.AesUtil;
import com.example.common.utils.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author 罗文斌
 * @Date 2023/7/25
 * @Version 1.0.0
 */
@ServerEndpoint("/sock/{id}")
@Component
@Slf4j
public class SocketController {

    private int online = 0;
    private String userId = "";
    private ConcurrentHashMap<String, Session> socketSession = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        log.info("用户：{}，已上线", id);
        this.userId = id;
        if(socketSession.get(id) != session) {
            socketSession.put(id, session);
        }
        this.online++;
        log.info("当前在线人数：{}", this.online);
    }

    @OnClose
    public void onClose() {
        log.info("用户{}，下线", this.userId);
        log.info("当前在线人数：{}", this.online);
    }

    @OnError
    public void onError(Throwable error) {
        log.error("socket连接出错：", error);
    }

    @OnMessage
    public void onMessage(String message) {
        String decrypt = null;
        try {
            decrypt = AesUtil.decrypt(message);
        } catch (Exception e) {
            log.error("消息解密失败：", e);
        }
        Map<String, String> msg = Util.transformParams(decrypt);
        String toUserId = msg.get("to");
        Session session = socketSession.get(toUserId);
        if(ObjectUtils.isEmpty(session)) {
            log.warn("用户{}已离线", toUserId);
            // 离线用户消息持久化处理
        }else {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("消息发送失败：", e);
            }
        }
    }
}
